using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Reflection;

public class CJson
{
    public string ToJsonString<T>(string jsonName, IList<T> iL)
    {
        StringBuilder Json = new StringBuilder();
        Json.Append("{" + jsonName + ":[");
        if (iL.Count > 0)
        {
            for (int i = 0; i < iL.Count; i++)
            {
                T obj = Activator.CreateInstance<T>();
                Type type = obj.GetType();
                PropertyInfo[] pis = type.GetProperties();
                Json.Append("{");
                for (int j = 0; j < pis.Length; j++)
                {
                    string ILValue = "";
                    if (pis[j].GetValue(iL[i], null) != null)
                    {
                        ILValue = pis[j].GetValue(iL[i], null).ToString().Replace("'", "\"").Replace("\r", "").Replace("\n", "").Replace("\\", "\\\\");
                    }
                    Json.Append("'" + pis[j].Name+ "':'" + ILValue + "'");
                    if (j < pis.Length - 1)
                    {
                        Json.Append(",");
                    }
                }
                Json.Append("}");
                if (i < iL.Count - 1)
                {
                    Json.Append(",");
                }
            }
        }
        Json.Append("]}");
        return Json.ToString();
    }

    public static string DtToJson(DataTable dt)
    {
        StringBuilder jsonBuilder = new StringBuilder();
        jsonBuilder.Append("{'tableName':'");
        jsonBuilder.Append(dt.TableName);
        jsonBuilder.Append("','totalCount':");
        jsonBuilder.Append(dt.Rows.Count);
        jsonBuilder.Append(",'data':[");
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            jsonBuilder.Append("{");
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                jsonBuilder.Append("'");
                jsonBuilder.Append(dt.Columns[j].ColumnName);
                jsonBuilder.Append("':'");
                jsonBuilder.Append(dt.Rows[i][j].ToString());
                jsonBuilder.Append("',");
            }
            jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
            jsonBuilder.Append("},");
        }
        jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
        jsonBuilder.Append("]");
        jsonBuilder.Append("}");
        return jsonBuilder.ToString();
    }
}